var amapFile = require('../../libs/amap-wx.js');
var util = require('../../libs/util.js');
var log = require('../log.js');
var amap, mapCtx;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    submiting:false,
    orderId:"",
    driverId: "",
    vehicleId:"",
    latitude: 0,//纬度 
    longitude: 0,//经度 
    speed: 0,//速度 
    accuracy: 16,//位置精准度 
    navLat: 0,//导航纬度 
    navLon: 0,//导航经度 
    markers: [],
    polyline: [],
    controls: [],
    "include-points": [],
    target_address:"暂无地址信息",
    target_distance:"距离目的地大约0公里，预计耗时：0时0分",
    imgList:[]
  },

  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onReady: function (e) {
    mapCtx = wx.createMapContext('map');
  },
  onLoad: function (e) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          middle_height: res.windowHeight - 102,
          client_width: res.windowWidth,
          client_height: res.windowHeight
        });
      }
    });
    that.setData({
      orderId:e.id,
      server:app.server
    });

    that.getLocation();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initMap(this.data.orderId);
  },
  getLocation(callback){
    var that = this;
    //获取手机定位坐标
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res.latitude)
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.setData({
          longitude: longitude,
          latitude: latitude
        });
        if(callback){
          callback(longitude, latitude)
        }
      }
    });
  },
  regionchange : function (res) {
    var that = this;
    mapCtx.getCenterLocation({
      success: function (res) {
        var y = res.longitude;
        var x = res.latitude;
        that.setData({
          locationLongitude: y,
          locationLatitude: x
        })
      }
    })
  },
  iotBox: function (driver_status) {
    var that = this;
    //定时关闭，以检测盒子是否在线
    setInterval(function(){
      //智冷盒状态
      that.setData({
        iot_box_on: false
      })
    },300000);
    // app.socket.on('iot', function (data) {
    //   if (data.iotbox != that.data.iotbox){
    //      return false;
    //   };
    //   if (data.ID != that.data.orderId) {
    //     return false;
    //   };
    //   console.log(data)
      

    //   if (data.iotType == "PS") {
    //     app.globalData.latitude = data.latitude;
    //     app.globalData.longitude = data.longitude;
    //     //console.log(data)
    //     //if (!that.data.app_gps_first){
    //       that.setCurrentLocation(data.latitude, data.longitude, data.speed||0, data.delivery_mile, data.delivery_time);
    //       //}
    //       //wx.setStorage({ key: that.data.orderId + '_gps', data: data.latitude + '_' + data.longitude + '|' + ((Number(data.delivery_mile) || 0) / 1000).toFixed(1) + '|' + (Number(data.delivery_time) || 0).toFixed(2)});
    //   };
    // });
    // app.socket.on('disconnect', function () {
    //   console.log('socket disconnected');
    // });
  },
  setCurrentLocation: function (x, y, speed, delivery_mile, delivery_time){
    var that = this;
    that.setData({
      delivery_mile: ((Number(delivery_mile)||0) / 1000).toFixed(1),
      delivery_time: (Number(delivery_time)||0).toFixed(2),
      speed:speed,
      longitude: y,
      latitude: x//,
      //polyline: that.data.polyline
    });
    //console.log(that.data.markers)
    mapCtx.translateMarker({
      markerId: 888,
      autoRotate: false,
      duration: 1,
      destination: {
        latitude: x,
        longitude: y
      }
    });
  },
  toRad : function (d) {
    return d * Math.PI / 180;
  },
  getDisance : function (lat1, lng1, lat2, lng2, that) {
    var dis = 0;
    var radLat1 = that.toRad(lat1);
    var radLat2 = that.toRad(lat2);
    var deltaLat = radLat1 - radLat2;
    var deltaLng = that.toRad(lng1) - that.toRad(lng2);
    var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6371393;
  },
  initMap: function (id) {
    var that = this, controls = [];
    var markers = [], lalt = [];

    amap = new amapFile.AMapWX({ key: 'a404e7cb1dcd34bb623e46fc3e46691e' });

    wx.showLoading({
      title: '数据加载中...',
    });
    
    wx.request({
      url: app.server+'/atapi/containeryard/containeryard/getCYByDelivery',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Cookie':app.globalData.cookie
      },
      data: {
        id: id,
        openid: app.globalData.openid
      },
      success: function (res) {
        wx.hideLoading();
        setTimeout(function(){
          wx.hideLoading();
        },100)
        console.log(res.data);
        if (res.data.success) {
          that.setData(res.data.data[0]);
          if(that.data.cy_image){
            that.setData({
              imgList:that.data.cy_image.split(",")
            })
          }

          //智冷盒数据
          that.iotBox(); 

          that.nextPointReachTime();

          //运单导航坐标
          if (that.data.coord){
            var coord = String(that.data.coord).split(',');
            that.setData({
              navLat: coord[0],
              navLon: coord[1]
            });
          }
        }
      }
    });
  },
  nextPointReachTime: function (callback) {
    var that = this;
    var getLBSTime = 0, getLBSResult = false;
    var lsbtInterval = setInterval(function(){
      if (getLBSResult){
        clearInterval(lsbtInterval);
      }
      if (getLBSResult == false && getLBSTime > 30){
        wx.showModal({
          title: "温馨提示",
          content: "获取你的位置失败，请确认打开手机的位置信息（不同手机叫法不一样，或者定位服务，或者GPS。）。如果还是获取失败，请到附件空地上，避免障碍物影响到卫星信号，导致获取位置失败。",
          showCancel: false,
          confirmText: "确定",
          success: function (res) {
            
          }
        });
        clearInterval(lsbtInterval);
      } 
      getLBSTime++;
      console.log(getLBSTime)
    },1000);
    that.getLocation(function (longitude, latitude) {
      getLBSResult = true;
      try{
        var coord = String(that.data.coord).split(",");
        util.getData("/xypapi/map/routerCalculate/getDrivingPathOfCoord", {
          lon: that.data.iotbox?app.globalData.longitude:longitude,
          lat: that.data.iotbox?app.globalData.latitude:latitude,
          nextLon: coord[1],
          nextLat: coord[0]
        }, function (res) {
          var distance = 0;
          if (res.data.success) {
            distance = res.data.data.distance;
            var duration = res.data.data.duration / 60;
            var _hour = Math.floor(duration / 60);
            var _minute = Number(duration - _hour * 60).toFixed(0);
            that.setData({
              target_address: "目的地："+that.data.address,
              target_distance: "距离目的地大约" + Number(distance / 1000).toFixed(1) + "公里，预计耗时：" + _hour + "时" + _minute+"分"
            })
          }
          if (callback) callback(distance);
        });
      }catch(e){};
    });
  },
  geocode: function () {
    var that = this;
    that.getLocation(function (longitude, latitude) {
      util.getData("/xypapi/map/routerCalculate/geocode", { longitude: longitude, latitude: latitude }, function (res) {
        if (res.data.success) {
          that.setData({
            target_address: "你所在位置：" + res.data.data,
            target_distance: '无目标计算距离'
          })
        }
      });
    });
  },
  navigation: function (e) {
    if (this.data.navLat) {
      wx.openLocation({
        latitude: parseFloat(this.data.navLat),
        longitude: parseFloat(this.data.navLon),
        scale: 28
      })
    }else{
      wx.showToast({ title: '没有坐标数据', image: '/images/wrong.svg', duration: 2000 });
    }
  },
  getContaineryard:function(){
    var that = this;

    that.setData({
      submiting:true
    });
    wx.showLoading({
      title: '提交中...'
    });

    that.nextPointReachTime(function (distance) {
      util.putData("/atapi/containeryard/containeryard/getContaineryard", {
        id: that.data.orderId
      }, function (res, error) {
        console.log(res); console.log(error)
        if (error) {
          wx.hideLoading(); wx.showToast({ title: '更新状态失败', image: '/images/wrong.svg', duration: 2000 });
          return false;
        }
        if (res.data.success) {
          wx.hideLoading();
          //轨迹
          app.updateDriverTrace(that.data.orderId, '已取到集装箱', "车辆已经在【"+that.data.name+"】取到货柜", 
          that.data.latitude + ',' + that.data.longitude, '', '', '', '', 0, 'yc', distance);
          wx.showModal({
            title: "温馨提示",
            content: "请按预约时间赶到仓库装货，如未预约请在卡口页面预约。",
            showCancel: false,
            confirmText: "确定",
            success: function (res) {
              that.initMap(that.data.orderId);
            }
          });
        } else {
          wx.hideLoading(); wx.showToast({ title: '更新状态失败', image: '/images/wrong.svg', duration: 2000 });
        }
        that.setData({
          submiting: false
        });
      });
    });
  },
  callManager:function(e){
    var that = this;
    var tel = that.data.tel;
    if(!tel){
      wx.showToast({ title: '暂无联系电话', image: '/images/wrong.svg', duration: 2000 });
      return false;
    }
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },
  gotoDelivery: function () {
    wx.redirectTo({
      url: '/pages/driver/currentOrder?id='+this.data.orderId
    })
  },
  gotoLP: function () {
    wx.redirectTo({
      url: '/pages/loadingplatform/loading_platform_driver?id='+this.data.lpId
    })
  },
  gotoHome: function () {
    wx.redirectTo({
      url: '/pages/driver/orderList'
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  showPictrue: function (e) {
    var image = e.currentTarget.dataset.image;
    wx.previewImage({
      urls: image
    })
  },
  submitCyImage:function(){
    var that = this;

    if(that.data.imgList.length > 0){
      wx.showLoading({
        title: '提交中...'
      });
  
      util.putData("/atapi/containeryard/containeryard/saveCyImage", {
        id: that.data.orderId,
        cy_image:that.data.imgList.join(",")
      }, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading();
        if (error) {
          wx.showToast({ title: '保存失败', image: '/images/wrong.svg', duration: 2000 });
          return false;
        }
        if (res.data.success) {
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              setTimeout(function(){
                that.initMap(that.data.orderId);
              },2000)
            }
          });
        } else {
          wx.showToast({ title: '保存失败', image: '/images/wrong.svg', duration: 2000 });
        }
      });
    }else{
      that.hideModal()
      wx.showToast({ title: '没有上传单据', image: '/images/wrong.svg', duration: 2000 });
    }
    
  },
  previewImage: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var current = e.currentTarget.dataset.url
    var imgList = that.data.imgList;
    wx.previewImage({
      current: current,
      urls: imgList
    })
  },
  chooseImage: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var imgList = [];
    try{
      var formData = {
        'id': that.data.orderId,
        'type':'cy_image'
      };
    }catch(e){}
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server +'/atapi/containeryard/containeryard/uploadImage',
          header:{
            'Authorization': app.globalData.token
          },
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: formData,
            success: function (res) {
              var data = JSON.parse(res.data); console.log(data)
              if (data.success) {
                imgList.push(data.data);
                imgList = util.arrayDeleteEmpty(imgList);
                that.setData({
                  imgList: imgList
                });
              }else{
                wx.showToast({
                  title: "上传失败",
                  image: '/images/wrong.png',
                  duration: 2000
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          })
      }
    })
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = that.data.imgList;
    var url = imgList[index];
    wx.showLoading({
      title: '删除中...'
    });
    if(url == ''){
      if (imgList.length == 1) {
        imgList = [];
      } else {
        imgList.splice(index, 1);
      }
      that.setData({
        imgList: imgList
      })
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000,
        success: function () {

        }
      });
      return false;
    }
    util.putData("/atapi/containeryard/containeryard/deleteFile", {
      url: url
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        if (imgList.length == 1) {
          imgList = [];
        } else {
          imgList = util.arrayDeleteWithIndex(imgList, index,1);
        }
        that.setData({
          imgList: imgList
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            
          }
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})